from django.http import HttpResponse
from PIL import Image, ImageDraw, ImageFont
import random
import string
import io
import base64
from project.settings import os, BASE_DIR

def generate_captcha():
    width, height = 120, 50
    image = Image.new('RGB', (width, height), color = (255, 255, 255))
    draw = ImageDraw.Draw(image)

    # 指定字体和字体大小
    try:
        font = ImageFont.truetype(os.path.join(BASE_DIR, 'apps/common/font/Open Sans Regular 400.ttf'), 36)  # 使用系统中的Arial字体，大小为36
    except IOError:
        font = ImageFont.load_default()  # 如果Arial字体不可用，则使用默认字体

    captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
    text_width, text_height = draw.textsize(captcha_text, font=font)
    text_x = (width - text_width) / 2
    text_y = (height - text_height) / 2
    draw.text((text_x, text_y), captcha_text, font=font, fill=(0, 0, 0))
    for _ in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)
        draw.line((x1, y1, x2, y2), fill=(0, 0, 0), width=2)
    
    # 写入文件
    img_io = io.BytesIO()
    # 保存图片
    image.save(img_io, 'PNG')
    # 从BytesIO中获取图片数据
    img_byte = img_io.getvalue()
    # 将图片转换为base64格式
    img_base64 = base64.b64encode(img_byte)
    # 将base64编码转换为字符串
    img_base64_str = img_base64.decode('utf-8')
    # print('captcha_text', captcha_text, img_base64_str)
    return captcha_text, img_base64_str